package com.tianyi.util;

import com.tianyi.model.SimpleLoginUser;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cuixuhui
 * @date 2019/11/21
 */
public class SimpleUserUtils {

    private static Logger logger = LoggerFactory.getLogger(SimpleUserUtils.class);

    public static String USER_TOKEN = "USER_TOKEN";


    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * 保存Cookies
     *
     * @param response  servlet请求
     * @param value     保存值
     */
    public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int time) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(name, value);
        // tomcat下多应用共享
        cookie.setPath("/");
        // 如果cookie的值中含有中文时，需要对cookie进行编码，不然会产生乱码
        try {
            URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        cookie.setMaxAge(time);
        // 将Cookie添加到Response中,使之生效
        // addCookie后，如果已经存在相同名字的cookie，则最新的覆盖旧的cookie
        response.addCookie(cookie);
        return response;
    }

    /**
     * @param request
     * @param response
     */
    public static final void deleteCookieByName(HttpServletRequest request, HttpServletResponse response, String deleteKey) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        if (MapUtils.isEmpty(cookieMap)){
            logger.info("deleteCookieByName cookieMap is empty deleteKey={}",deleteKey);
            return;
        }
        if (!cookieMap.keySet().contains(deleteKey)){
            logger.info("deleteCookieByName deleteKey={} is not exist cookie map",deleteKey);
            return;
        }
        cookieMap.forEach((k,v) -> {
            if (!StringUtils.equals(k, deleteKey)) {
                return;
            }
            Cookie cookie = cookieMap.get(k);
            //设置cookie有效时间为0
            cookie.setMaxAge(0);
            //不设置存储路径
            cookie.setPath("/");
            response.addCookie(cookie);
        });
    }

    public static final void addUser2Cookie(HttpServletResponse response, SimpleLoginUser loginUser){

        String userEncryptionCode = EncryptUtil.userEncryption(loginUser);
        logger.info("addUser2Cookie deSencodeUser={}", userEncryptionCode);
        setCookie(response, USER_TOKEN, userEncryptionCode, 86400);
    }

    public static final SimpleLoginUser getUserFromReq(HttpServletRequest request){

        Map<String, Cookie> cookieMap = readCookieMap(request);
        if (MapUtils.isEmpty(cookieMap)){
            logger.info("getUserFromReq cookieMap is empty");
            return null;
        }
        Cookie cookie = cookieMap.get(USER_TOKEN);
        String value = cookie.getValue();
        return EncryptUtil.userDecrypt(value);
    }
}
